package com.itchen.headline.controller;

import com.itchen.headline.common.Result;
import com.itchen.headline.pojo.NewsHeadline;
import com.itchen.headline.service.NewsHeadlineService;
import com.itchen.headline.service.impl.NewsHeadlineServiceImpl;
import com.itchen.headline.util.JwtHelper;
import com.itchen.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController{
    private NewsHeadlineService newsHeadlineService = new NewsHeadlineServiceImpl();

    /**
     * 发布文章
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void publish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从前端数据头中获取token
        String token = req.getHeader("token");
        Long userId = JwtHelper.getUserId(token);

        // 从请求中接收数据（newsHeadline）
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadline.setPublisher(userId.intValue());

        // 将信息存入数据库
        newsHeadlineService.addNewsHeadline(newsHeadline);

        // 响应给前端
        WebUtil.writeJson(resp, Result.ok(null));

    }

    /**
     * 修改文章 回显
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findHeadlineByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));
        NewsHeadline newsHeadline = newsHeadlineService.findHeadlineByHid(hid);

        Map data = new HashMap();
        data.put("headline",newsHeadline);
        WebUtil.writeJson(resp,Result.ok(data));
    }

    /**
     * 更新文章
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadlineService.update(newsHeadline);

        WebUtil.writeJson(resp,Result.ok(null));
    }

    /**
     * 删除文章
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));

        newsHeadlineService.removeByHid(hid);
        WebUtil.writeJson(resp,Result.ok(null));
    }
}
